﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace ES.Interceptor
{
    public static class MethodHookFactory
    {
        public static IMethodHook Create()
        {
            var clrVersion = RuntimeEnvironment.GetSystemVersion().Substring( 1 ); // delete the initial 'v' character
            return Create( new Version( clrVersion ) );
        }

        public static IMethodHook Create( Version frameworkVersion )
        {
            IMethodHook methodHook;

            if ( frameworkVersion >= FrameworkVersions.Net20SP2 )
            {
                if ( Is32Bit() )
                {
                    methodHook = new MethodHook32();
                }
                else
                {
                    throw new ApplicationException( "Processor is not supported" );
                }
            }
            else
            {
                var msg = String.Format( "The CLR version {0} is not supported", frameworkVersion );
                throw new ApplicationException( msg );
            }

            return methodHook;
        }

        #region - private methods -
        private static Boolean Is32Bit()
        {
            Boolean is32Bit;
            if ( IntPtr.Size == 4 )
            {
                is32Bit = true;
            }
            else if ( IntPtr.Size == 8 )
            {
                is32Bit = false;
            }
            else
            {
                // The future is now!
                throw new ApplicationException( "Is32Bit" );
            }
            return is32Bit;
        }
        #endregion
    }
}
